Skip to content

ImageDecoder: true streaming Open/OpenAsync(Stream), DecodeAsync/CopyPixelsAsync - #15

Merged
sdcb merged 1 commit into
mainfrom
streaming/image-decoder
Nov 23, 2026
Merged

sdcb merged 1 commit into
mainfrom
streaming/image-decoder

Conversation

@sdcb

@sdcb sdcb commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Summary

ImageDecoder.Open(Stream) / OpenAsync(Stream) no longer copy the stream whole first (unit 12 of the streaming work).

  • Open sniffs 4 KiB, then reads the header with the codec's row reader (ImageDecoderRegistration.CreateRowReader). Format and frame 0's Info are available right away.
  • The first full-size Decode / CopyPixels of frame 0 reads its rows straight from the stream. Decode builds a RasterImage in the codec's own layout (PixelFormat.ForChannels(info.Channels, info.SampleFormat), plus the header's bit depth and colour encoding); a test checks that this equals TryDecode for PNG and JPEG.
  • Every other operation (a second decode, a region / scale / orientation, other frames, metadata, a thumbnail) first reads the whole file and takes the existing span path, so results equal Open(byte[]). A seekable stream gets the file by seeking; a non-seekable one replays the bytes it kept as it read them.
  • Codecs without a row reader (every real codec today) read the whole file at open, exactly as before.
  • New Open(Stream, leaveOpen, forwardOnly) / OpenAsync(Stream, leaveOpen, forwardOnly, ct). With forwardOnly, the bytes a streamed decode reads are not kept; a later revisit throws InvalidOperationException.
  • OpenAsync reads the header asynchronously, then prefetches the rest of a non-seekable stream in the background. New ImageFrame.DecodeAsync / CopyPixelsAsync stream truly, starting from wherever the prefetch has got to. Sync Decode / CopyPixels block on the asynchronous reads and never read the stream synchronously (Kestrel-safe), and their token cancels that wait. Dispose cancels the prefetch; with leaveOpen it also waits for the cancelled read to finish before returning the stream to the caller.
  • StreamTap (new, internal) is the session's only handle on the stream. It reads by offset and keeps the bytes it has read for replay. A SemaphoreSlim lets one stream read run at a time, and a lock guards the kept bytes and counters.
  • On browser/WASI, OpenAsync reads the whole stream at open, because a synchronous call cannot block there.

Tests

  • tests/Sdcb.SimdCodecs.Tests/Streaming/ImageDecoderStreamingTests.cs covers: every operation sequence equals Open(byte[]) over a 1-byte stream, random chunks, MemoryStream and FileStream, for both the streaming and the fallback variant of RawStreamCodec; real PNG/JPEG on every source, with and without forwardOnly; a request body (async-only ChunkedStream) with DecodeAsync and with legacy Decode; prefetch racing DecodeAsync; dispose during the prefetch; cancellation (async, and sync-over-async); truncated streams throw InvalidDataException; leaveOpen; pooled decode. AllocatesLessThan checks that seekable and forward-only Open + CopyPixels of a 4 MB image allocate less than 1/8 of the file.
  • Breaking the streaming path on purpose makes the streaming-specific tests fail.
  • Full suite: 7090 tests, 0 failed. Streaming and session tests also pass with DOTNET_EnableAVX2=0 and DOTNET_EnableHWIntrinsic=0.
  • The AOT/wasm smoke now also covers OpenAsync + DecodeAsync, CopyPixelsAsync and forward-only Open + CopyPixels. NativeAOT and Mono AOT (browser-wasm) output is identical to the JIT's.

Notes for the coordinator

  • PublicAPI.Unshipped.txt: 4 contiguous lines appended, so a line conflict with PR Facade: OpenRowReader(Async) and CreateEncoder(Stream) streaming entry points #12 is likely.
  • No change to ImageCodecs*.cs: the codec sniff is private (ImageDecoder.Probe). When two registrations share a format (GainMap before plain JPEG), the session does not stream and reads the whole file.
  • ImageFrame.Info for frame 0 of a stream session comes from the header reader, which may not see values stored after the pixels (for example a trailing eXIf orientation). Region / scale / orientation copies size the destination from the whole file's frame info. A plain full-size copy uses the header's size, which is all a streamed decode can know. This is documented on ImageFrame.Info.
  • When a codec takes UseBufferedFallback, Open lets the row reader decode the file whole and then discards that result before the span path decodes it again. This costs double for unstreamable variants (progressive JPEG, Adam7) once codecs add row readers. Avoiding it needs an Abstractions hook (header-only initialise) that this unit may not add.
  • A forward-only streamed Decode puts only the metadata found before the pixels into the image.

🤖 Generated with Claude Code

…frame 0

Open(Stream) no longer copies the stream whole. It sniffs 4 KiB, reads the
header through the codec's row reader (ImageDecoderRegistration.CreateRowReader)
and, for a still file, decodes frame 0's first full-size Decode / CopyPixels
straight from the stream. Every other operation reads the whole file first
(seeking, or replaying the bytes a non-seekable stream kept) and takes the span
path, so results equal Open(byte[]). Codecs without a row reader are read whole
at open, as before.

- Open(Stream, leaveOpen, forwardOnly) / OpenAsync(..., forwardOnly, ct):
  forwardOnly keeps nothing a streamed decode reads; later revisits throw
  InvalidOperationException.
- OpenAsync reads the header asynchronously, then prefetches the rest in the
  background. New ImageFrame.DecodeAsync / CopyPixelsAsync stream alongside the
  prefetch; sync Decode / CopyPixels wait for it and never read synchronously.
- StreamTap: one hold on the stream, by offset, with a recorded prefix/whole
  for replay; prefetch and readers serialised by a semaphore.
- Tests: ImageDecoderStreamingTests (RawStreamCodec + real codecs); the AOT and
  wasm smoke tests cover the new entry points.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sdcb
sdcb merged commit 59fce0a into main Nov 23, 2026
15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant